import QCSettings from "../utils/QuickCommandSettings";
import { location } from "../utils/getLocation";
import { DrawString, RemoveEmoji, copyToClipboard, getItemFromGui, getItemSBID, getItemUUID, getcmdfromchat } from "../utils/utils";
import { AddData, SavedData } from "../utils/data";
import playCMD from "./playCMD";
import itemLock from "./itemLock";
import { InstanceStats } from "./dungeon";
import settings from "../utils/settings";


export function quickcommandInit() {
    register("guiKey", (char,key,gui,event) => {
        if(!QCSettings .CopyNBT) return;
        if(!Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || key != Keyboard.KEY_C) return;
        let item = getItemFromGui(gui);
        if(!item) return;
        let nbtObj = item.getNBT().toObject();
        copyToClipboard(JSON.stringify(nbtObj,null,4),"§6§l[BZA] §a物品的NBT已成功复制到剪贴板");
    })
}

AddData("qcKeyBind",0);
const bzaqc = new KeyBind("bza按键快捷指令",SavedData.qcKeyBind,"BabayzombieAddons - ChatTriggers Module");
register("step",()=>{SavedData.qcKeyBind = bzaqc.getKeyCode()}).setDelay(10);

register("guiKey", (char,key,gui,event) => {
    if(!QCSettings.itemLock || !location.inSkyblock) return;
    if(key != bzaqc.getKeyCode()) return;
    let item = getItemFromGui(gui);
    if(!item) return;
    let id = getItemUUID(item);
    if(!id) return;
    itemLock.toggleItem(id);
})

let followcmd = null;
let followcmdt = null;
register("chat", (message,server,event) => {
    if(server == "Private Island" || server == "Garden") return;
    followcmd = getcmdfromchat(event,"FOLLOW");
    if(followcmd) followcmdt = Date.now();
}).setCriteria("${message} is traveling to ${server} FOLLOW")

let callcmd = null;
let callcmdt = null;
register("chat", (ring,event) => {
    if(!location.inSkyblock) return;
    callcmd = getcmdfromchat(event,"[PICK UP]");
    if(settings.AutoAnswer) {
        ChatLib.say(callcmd);
        callcmd = null;
        return;
    }
    if(callcmd) callcmdt = Date.now();
}).setCriteria(/✆ (RING|BUZZ)...  \[PICK UP\]/)

let ahcmd = null;
let ahcmdt = null;
register("chat", (message,event) => {
    if(location.inDungeon || location.inKuudra) return;
    ahcmd = getcmdfromchat(event,"CLICK");
    if(ahcmd) ahcmdt = Date.now();
}).setCriteria("[Auction] ${message} CLICK")

const keyBindSneak = new KeyBind(Client.getMinecraft().field_71474_y.field_74311_E)


let cmdReadyToDo = [];

//指令轮盘Gui
function drawRing(color,x,y,startradius,radius,startangle,angle) {
    for (let i = startangle; i < startangle + angle; i+=0.5) {
        let x1 = startradius * Math.sin(i*Math.PI/180);
        let y1 = startradius * Math.cos(i*Math.PI/180);
        let x2 = startradius * Math.sin((i+1)*Math.PI/180);
        let y2 = startradius * Math.cos((i+1)*Math.PI/180);
        let x3 = radius * Math.sin(i*Math.PI/180);
        let y3 = radius * Math.cos(i*Math.PI/180);
        let x4 = radius * Math.sin((i+1)*Math.PI/180);
        let y4 = radius * Math.cos((i+1)*Math.PI/180);
        new Shape(color).addVertex(x+x1,y+y1).addVertex(x+x2,y+y2).addVertex(x+x3,y+y3).addVertex(x+x4,y+y4).setDrawMode(6).draw();
    }
}
function drawStringOnGui(string,x,y,s) {
    let length = 0;
    for (let i = 0; i < string.removeFormatting().length; i++) {
        string.removeFormatting().charCodeAt(i) > 255 ? length += 2 : length += 1;
    }
    DrawString(string,x - length * 2 * s,y,s,true);
}

const commandGui = new Gui();
commandGui.registerDraw((mx,my,tick) => {
    let mouseRadius = Math.atan2(mx - Renderer.screen.getWidth() / 2, my - Renderer.screen.getHeight() / 2) * 180 / Math.PI;
    Renderer.drawCircle(Renderer.color(0,0,0,50), Renderer.screen.getWidth() / 2, Renderer.screen.getHeight() / 2, 300 / Renderer.screen.getScale(), 360,5);
    Renderer.drawCircle(Renderer.color(0,0,0,100), Renderer.screen.getWidth() / 2, Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 720,0);
    for (let i = 30; i < 360; i+=60) {
        let x1 = 120 / Renderer.screen.getScale() * Math.sin(i*Math.PI/180);
        let y1 = 120 / Renderer.screen.getScale() * Math.cos(i*Math.PI/180);
        let x2 = 300 / Renderer.screen.getScale() * Math.sin(i*Math.PI/180);
        let y2 = 300 / Renderer.screen.getScale() * Math.cos(i*Math.PI/180);
        Renderer.drawLine(Renderer.color(0,0,0,100),Renderer.screen.getWidth() / 2 + x1,Renderer.screen.getHeight() / 2 + y1,Renderer.screen.getWidth() / 2 + x2,Renderer.screen.getHeight() / 2 + y2,1,1);
    }

    drawStringOnGui("§e松开按键执行对应指令",Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2 - 350 / Renderer.screen.getScale(),1.5);
    drawStringOnGui(cmdReadyToDo[0][0],Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2 - 10 * Renderer.screen.getScale(),1.5);
    drawStringOnGui(cmdReadyToDo.length > 1 ? cmdReadyToDo[1][0] : cmdReadyToDo[0][0],Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2 - 210 / Renderer.screen.getScale(),1.5);
    drawStringOnGui("§c取消执行指令",Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2 + 210 / Renderer.screen.getScale(),1.5);
    drawStringOnGui(QCSettings.GuiCommand1.split("\n")[0],Renderer.screen.getWidth() / 2 + 210 / Renderer.screen.getScale() * Math.sin(240*Math.PI/180),Renderer.screen.getHeight() / 2 + 210 / Renderer.screen.getScale() * Math.cos(240*Math.PI/180),1.5);
    drawStringOnGui(QCSettings.GuiCommand2.split("\n")[0],Renderer.screen.getWidth() / 2 + 210 / Renderer.screen.getScale() * Math.sin(300*Math.PI/180),Renderer.screen.getHeight() / 2 + 210 / Renderer.screen.getScale() * Math.cos(300*Math.PI/180),1.5);
    drawStringOnGui(QCSettings.GuiCommand3.split("\n")[0],Renderer.screen.getWidth() / 2 + 210 / Renderer.screen.getScale() * Math.sin(120*Math.PI/180),Renderer.screen.getHeight() / 2 + 210 / Renderer.screen.getScale() * Math.cos(120*Math.PI/180),1.5);
    drawStringOnGui(QCSettings.GuiCommand4.split("\n")[0],Renderer.screen.getWidth() / 2 + 210 / Renderer.screen.getScale() * Math.sin(60*Math.PI/180),Renderer.screen.getHeight() / 2 + 210 / Renderer.screen.getScale() * Math.cos(60*Math.PI/180),1.5);
    
    switch (true) {
        case Math.sqrt((mx - Renderer.screen.getWidth() / 2)**2 + (my - Renderer.screen.getHeight() / 2)**2) < 120 / Renderer.screen.getScale():
            Renderer.drawCircle(Renderer.color(255,255,255,30), Renderer.screen.getWidth() / 2, Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 360,5);
            break;
        case Math.abs(mouseRadius) < 30:
            drawRing(Renderer.color(255,255,255,30),Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 300 / Renderer.screen.getScale(), -30,60);
            break;
        case mouseRadius > -90 && mouseRadius < -30:
            drawRing(Renderer.color(255,255,255,30),Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 300 / Renderer.screen.getScale(), -90,60);
            break;
        case mouseRadius > -150 && mouseRadius < -30:
            drawRing(Renderer.color(255,255,255,30),Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 300 / Renderer.screen.getScale(), -150,60);
            break;
        case mouseRadius < 90 && mouseRadius > 30:
            drawRing(Renderer.color(255,255,255,30),Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 300 / Renderer.screen.getScale(), 30,60);
            break;
        case mouseRadius < 150 && mouseRadius > 30:
            drawRing(Renderer.color(255,255,255,30),Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 300 / Renderer.screen.getScale(), 90,60);
            break;
        default:
            drawRing(Renderer.color(255,255,255,30),Renderer.screen.getWidth() / 2,Renderer.screen.getHeight() / 2, 120 / Renderer.screen.getScale(), 300 / Renderer.screen.getScale(), 150,60);
            break;
    }
    
    if(!Keyboard.isKeyDown(bzaqc.getKeyCode()) && cmdReadyToDo.length != 0) {
        Client.currentGui.close();
        switch (true) {
            case Math.sqrt((mx - Renderer.screen.getWidth() / 2)**2 + (my - Renderer.screen.getHeight() / 2)**2) < 120 / Renderer.screen.getScale():
                cmdReadyToDo[0][1]();
                break;
            case Math.abs(mouseRadius) < 30:
                break;
            case mouseRadius > -90 && mouseRadius < -30:
                let cmd2 = QCSettings.GuiCommand2.split("\n");
                if(cmd2.length > 1) {
                    cmd2.slice(1).forEach(c => {
                        if(c.startsWith("/")) ChatLib.command(c.replace("/",""),true); else ChatLib.command(c);
                    })
                } else {
                    if(cmd2[0].startsWith("/")) ChatLib.command(cmd2[0].replace("/",""),true); else ChatLib.command(cmd2[0]);
                }
                break;
            case mouseRadius > -150 && mouseRadius < -30:
                let cmd1 = QCSettings.GuiCommand1.split("\n");
                if(cmd1.length > 1) {
                    cmd1.slice(1).forEach(c => {
                        if(c.startsWith("/")) ChatLib.command(c.replace("/",""),true); else ChatLib.command(c);
                    })
                } else {
                    if(cmd1[0].startsWith("/")) ChatLib.command(cmd1[0].replace("/",""),true); else ChatLib.command(cmd1[0]);
                }
                break;
            case mouseRadius < 90 && mouseRadius > 30:
                let cmd4 = QCSettings.GuiCommand4.split("\n");
                if(cmd4.length > 1) {
                    cmd4.slice(1).forEach(c => {
                        if(c.startsWith("/")) ChatLib.command(c.replace("/",""),true); else ChatLib.command(c);
                    })
                } else {
                    if(cmd4[0].startsWith("/")) ChatLib.command(cmd4[0].replace("/",""),true); else ChatLib.command(cmd4[0]);
                }
                break;
            case mouseRadius < 150 && mouseRadius > 30:
                let cmd3 = QCSettings.GuiCommand3.split("\n");
                if(cmd3.length > 1) {
                    cmd3.slice(1).forEach(c => {
                        if(c.startsWith("/")) ChatLib.command(c.replace("/",""),true); else ChatLib.command(c);
                    })
                } else {
                    if(cmd3[0].startsWith("/")) ChatLib.command(cmd3[0].replace("/",""),true); else ChatLib.command(cmd3[0]);
                }
                break;
            default:
                if(cmdReadyToDo.length > 1) cmdReadyToDo[1][1](); else cmdReadyToDo[0][1]();
                break;
        }
        cmdReadyToDo = [];
    };
})

//按键触发器
bzaqc.registerKeyPress(() => {
    if(!Keyboard.isKeyDown(bzaqc.getKeyCode())) return;
    cmdReadyToDo = [];
    getQuickCommand();
    if(QCSettings.commandGui) {
        commandGui.open();
        return;
    }
    if(QCSettings.commandOnRelease || cmdReadyToDo.length == 0) return;
    cmdReadyToDo[0][1]();
    cmdReadyToDo = [];
});

bzaqc.registerKeyRelease(() => {
    if(QCSettings.commandGui) return;
    if(!QCSettings.commandOnRelease || cmdReadyToDo.length == 0) return;
    cmdReadyToDo[0][1]();
    cmdReadyToDo = [];
})

//快捷指令
function getQuickCommand() {
    let heldItem = null;
    if(Player.getHeldItem()){
        heldItem = Player.getHeldItem();
    }
    if(QCSettings.qcplay && location.server != "" && !location.inSkyblock) {
        cmdReadyToDo.push(["打开游玩菜单",()=>{ playCMD.openGUI(); }]);
    }
    if(QCSettings.qcfollow && Date.now() - followcmdt < 19500){
        cmdReadyToDo.push(["Skyblock 跟随",()=>{
            ChatLib.say(followcmd);
            followcmd = null; followcmdt = null;
        }])
    }
    if(QCSettings.qccall && Date.now() - callcmdt < 10000) {
        cmdReadyToDo.push(["接听电话",()=>{
            ChatLib.say(callcmd);
            callcmd = null; callcmdt = null;
        }])
    }
    if(QCSettings.qcah && Date.now() - ahcmdt < 60000) {
        cmdReadyToDo.push(["查看ah",()=>{
            ChatLib.say(ahcmd);
            ahcmd = null; ahcmdt = null;
        }])
    }
    if(QCSettings.gardenquickcommand && location.island == "Garden") {
        if(QCSettings.gardenquickcommand == 3 || (QCSettings.gardenquickcommand == 2 && Scoreboard.getLines().filter(e => RemoveEmoji(e.getName()).removeFormatting() == "Jacob's Contest").length == 1)) {
            cmdReadyToDo.push(["回到花园出生点",()=>{
                ChatLib.command("warp garden");
            }])
            cmdReadyToDo.push(["打开desk",()=>{
                ChatLib.command("desk");
            }])
        } else {
            cmdReadyToDo.push(["打开desk",()=>{
                ChatLib.command("desk");
            }])
            cmdReadyToDo.push(["回到花园出生点",()=>{
                ChatLib.command("warp garden");
            }])
        }
    }
    if(QCSettings.qcfishingbag && heldItem != null && (heldItem.getID() == 346.0 && getItemSBID(heldItem) != "GRAPPLING_HOOK")) {
        cmdReadyToDo.push(["打开钓鱼包",()=>{
            ChatLib.command("fishingbag");
        }])
    }
    if(QCSettings.qcbow != 0.0 && heldItem != null && heldItem.getID() == 261.0) {
        switch (QCSettings.qcbow) {
            case 1.0:
                cmdReadyToDo.push(["打开箭袋",()=>{
                    ChatLib.command("quiver");
                }])
                cmdReadyToDo.push(["打开护符包",()=>{
                    ChatLib.command("accessorybag");
                }])
                break;
            case 2.0:
                cmdReadyToDo.push(["打开护符包",()=>{
                    ChatLib.command("accessorybag");
                }])
                cmdReadyToDo.push(["打开箭袋",()=>{
                    ChatLib.command("quiver");
                }])
                break;
            }
    }
    if(QCSettings.instanceRequeue && InstanceStats.end && (InstanceStats.leader || InstanceStats.solo)) {
        cmdReadyToDo.push(["地牢 / kuudra 重开",()=>{
            ChatLib.command("instancerequeue");
        }])
    }
    if(QCSettings.kuudraWardrobe && location.inKuudra) {
        cmdReadyToDo.push(["打开衣柜",()=>{
            ChatLib.command("wardrobe");
        }])
    }
    if(QCSettings.CrystalNucleus && location.island == "Crystal Hollows") {
        cmdReadyToDo.push(["回晶核",()=>{
            ChatLib.command("warp nucleus");
        }])
    }
    if(QCSettings.mineshaft && location.island == "Mineshaft") {
        if(keyBindSneak.isKeyDown()) {
            cmdReadyToDo.push(["回营地",()=>{
                ChatLib.command(`warp camp`);
            }])
            cmdReadyToDo.push(["取出逃生绳",()=>{
                ChatLib.command("gfs ASCENSION_ROPE 1");
            }])
        } else {
            cmdReadyToDo.push(["取出逃生绳",()=>{
                ChatLib.command("gfs ASCENSION_ROPE 1");
            }])
            cmdReadyToDo.push(["回营地",()=>{
                ChatLib.command(`warp camp`);
            }])
        }
    }
    if(QCSettings.basecamp && location.island == "Dwarven Mines" && (location.location == "Dwarven Base Camp" || location.location == "Glacite Tunnels" || location.location == "Great Glacite Lake")) {
        cmdReadyToDo.push(["回营地",()=>{
            ChatLib.command(`warp camp`);
        }])
    }
    cmdReadyToDo.push(["/" + QCSettings.qcdefault,()=>{
        ChatLib.command(QCSettings.qcdefault);
    }])
    if(QCSettings.qcplay && location.server != "") {
        cmdReadyToDo.push(["打开游玩菜单",()=>{ playCMD.openGUI(); }]);
    }
}